let interstitialAd = null
const app = getApp()
import {
	get,
	getById
} from "../../utils/db.js"
import config from "../../utils/config"

Page({
	data: {
		activeIndex: 0,		//顶部tab选中下标
		typeList: [],	//分类列表
		list:[],			//图书列表
		appName: config.appName,
		isAd: config.isAd,
		page: 1,
		pageSize: 20

	},
	//点击顶部分类
	async typeClick(e) {
		let {
			index,
		} = e.currentTarget.dataset;
		
		//清除以前的数据
		this.data.list=[]
		this.data.page=1;
		this.data.activeIndex=index;

		//生成图书列表
		this.getList()
		this.setData({
			activeIndex: index
		})
	},
	async onLoad() {
		// 在页面onLoad回调事件中创建插屏广告实例
		if (wx.createInterstitialAd && config.isAd) {
			interstitialAd = wx.createInterstitialAd({
				adUnitId: 'adunit-c41d7d7535a297d5'
			})
			interstitialAd.onLoad(() => {})
			interstitialAd.onError((err) => {})
			interstitialAd.onClose(() => {})
		}

		// 在页面onLoad回调事件中创建插屏广告实例
		await this.getTypeList()
		//根据分类id获取图书列表
		let {
			_id
		} = this.data.typeList[0];
		await this.getList(_id)
	},
	//页面触底
	async onReachBottom() {
		this.data.page++;
		let {
			_id
		} = this.data.typeList[this.data.activeIndex];

		await this.getList(_id)
	},
	onShow() {
		// 在适合的场景显示插屏广告
		if (interstitialAd && config.isAd) {
			interstitialAd.show().catch((err) => {
				console.error(err)
			})
		}
	},
	//获取分类列表
	async getTypeList() {
		var result = await get({
			collection: "type"
		}).catch(err => {
			console.error(err)
		})
		var typeList = result.data;
		typeList.unshift({
			_id: "",
			name: "综合",
			_openid: wx.getStorageSync('openid'),
			addtime: new Date().getTime()
		})
		console.log(typeList);
		this.setData({
			typeList: typeList
		})
	},

	//获取某分类下的图书列表
	async getList() {
		//获取当前分类id
		var activeIndex=this.data.activeIndex;
		let {_id:typeid}=this.data.typeList[activeIndex]
		wx.showLoading({
			title: '正在加载',
		})
		let {
			page,
			pageSize
		} = this.data;
		//获取当前分类下的book
		var skip = pageSize * (page-1);
		var result = await get({
			collection: "book",
			where: {
				status: 1,
				typeid,
			},
			skip,
			limit: pageSize
		}).catch(err => {
			console.error(err)
		})
		wx.hideLoading()

		var list = this.data.list.concat(result.data)
		// console.log(list,"4444");return;
		// console.log(list)
		this.setData({
			list
		})


		wx.stopPullDownRefresh()

	},

	//下拉刷新
	onPullDownRefresh() {
		// this.data.list = [];

	},
	//跳转详情页
	toDetail(e) {
		console.log(e)
		var id = e.currentTarget.dataset.id
		wx.navigateTo({
			url: '/pages/detail/detail?id=' + id,
			fail: err => {
				console.log(err)
			}
		})
	},
	//页面分享
	onShareAppMessage() {
		return {
			title: app.globalData.appName
		}
	},
	//分享到朋友圈
	onShareTimeline() {
		return {
			title: "每天十分钟，每周一本书，一年五十本好书，跑步健身的时候都可以听书啦",
			imageUrl: "/images/book/share.jpg"
		}
	}
})